import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { UserProfile, UserSettings } from '@/types/user';
import { userApi } from '@/lib/api';

interface UserState {
  // 用户资料
  profile: UserProfile | null;
  // 用户设置
  settings: UserSettings | null;
  // 用户完整信息
  userData: any | null;
  // 是否正在加载
  isLoading: boolean;
  // 错误信息
  error: string | null;
  // 获取用户完整信息
  fetchUserData: () => Promise<void>;
  // 获取用户资料
  fetchUserProfile: () => Promise<void>;
  // 更新用户资料
  updateUserProfile: (data: Partial<UserProfile>) => Promise<void>;
  // 获取用户设置
  fetchUserSettings: () => Promise<void>;
  // 更新用户设置
  updateUserSettings: (data: Partial<UserSettings>) => Promise<void>;
  // 重置状态
  reset: () => void;
}

export const useUserStore = create<UserState>()(
  devtools(
    persist(
      (set, get) => ({
        profile: null,
        settings: null,
        userData: null,
        isLoading: false,
        error: null,

        // 获取用户完整信息
        fetchUserData: async () => {
          set({ isLoading: true, error: null });

          try {
            const userData = await userApi.getCurrentUser();
            
            set({
              userData,
              profile: userData.profile || null,
              settings: userData.settings || null,
              isLoading: false,
            });

            return userData;
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '获取用户信息失败';
            console.error('获取用户信息失败:', error);
            
            set({
              error: errorMessage,
              isLoading: false,
            });
            
            throw new Error(errorMessage);
          }
        },

        // 获取用户资料
        fetchUserProfile: async () => {
          set({ isLoading: true, error: null });

          try {
            const userData = await userApi.getCurrentUser();
            
            set({
              profile: userData.profile || null,
              isLoading: false,
            });

            return userData.profile;
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '获取用户资料失败';
            console.error('获取用户资料失败:', error);
            
            set({
              error: errorMessage,
              isLoading: false,
            });
            
            throw new Error(errorMessage);
          }
        },

        // 更新用户资料
        updateUserProfile: async (data: Partial<UserProfile>) => {
          set({ isLoading: true, error: null });

          try {
            const response = await userApi.updateUserProfile(data);
            
            set({
              profile: response.profile || null,
              isLoading: false,
            });

            return response.profile;
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '更新用户资料失败';
            console.error('更新用户资料失败:', error);
            
            set({
              error: errorMessage,
              isLoading: false,
            });
            
            throw new Error(errorMessage);
          }
        },

        // 获取用户设置
        fetchUserSettings: async () => {
          set({ isLoading: true, error: null });

          try {
            const userData = await userApi.getCurrentUser();
            
            set({
              settings: userData.settings || null,
              isLoading: false,
            });

            return userData.settings;
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '获取用户设置失败';
            console.error('获取用户设置失败:', error);
            
            set({
              error: errorMessage,
              isLoading: false,
            });
            
            throw new Error(errorMessage);
          }
        },

        // 更新用户设置
        updateUserSettings: async (data: Partial<UserSettings>) => {
          set({ isLoading: true, error: null });

          try {
            const response = await userApi.updateUserSettings(data);
            
            set({
              settings: response.settings || null,
              isLoading: false,
            });

            return response.settings;
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '更新用户设置失败';
            console.error('更新用户设置失败:', error);
            
            set({
              error: errorMessage,
              isLoading: false,
            });
            
            throw new Error(errorMessage);
          }
        },

        // 重置状态
        reset: () => {
          set({
            profile: null,
            settings: null,
            userData: null,
            isLoading: false,
            error: null,
          });
        },
      }),
      {
        name: 'user-storage',
        partialize: (state) => ({
          profile: state.profile,
          settings: state.settings,
        }),
      }
    )
  )
); 